<?php

namespace plugin\agent\app\admin\logic;

use app\common\logic\BaseLogic;
use app\model\user\User;
use plugin\agent\app\model\AgentLevel;
use plugin\agent\app\model\AgentUser;
use support\exception\BadException;
use support\utils\Time;

class AgentUserLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new AgentUser();
    }

    public function addByUser($input)
    {
        $user_id = $input['user_id'] ?? 0;
        if (!$user_id) {
            throw new BadException("用户ID错误");
        }

        $exists = $this->model->where([
            'user_id' => $user_id
        ])
            ->count();
        if ($exists > 0) {
            throw new BadException("用户已经是分销商了,不可重复操作");
        }

        $level_id = AgentLevel::where([
            'is_default' => 1
        ])->value('id');

        $model = new AgentUser();
        $model->save([
            'path' => "",
            'user_id' => $user_id,
            'status' => 1,
            'bind_time' => Time::now(),
            'level_id' => $level_id ?? 0,
        ]);

        User::update([
            'is_agent' => 1,
            'agent_id' => $model->agent_id,
        ], [
            'id' => $user_id,
        ]);

    }
}